package com.aiden.app.common.util

import android.app.Activity
import android.app.ActivityManager
import android.app.AppOpsManager
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View
import android.view.ViewGroup
import com.aiden.app.common.constant.PrefConstants
import com.aiden.app.common.extension.appOpsManager
import com.aiden.app.common.extension.getInt
import com.aiden.app.common.extension.notificationManager

object SystemUtil {

    /**
     * 判断进程是否运行
     * @param context
     * @return
     */
    fun isAppAlive(context: Context): Boolean {
        val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val list = manager.getRunningTasks(20)
        if (list[0].topActivity.packageName == "com.dahu.app") {
            return true
        } else {
            for (info in list) {
                if (info.topActivity.packageName == "com.dahu.app") {
                    return true
                }
            }
            return false
        }
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    fun isForeground(context: Context?, className: String): Boolean {
        if (context == null || android.text.TextUtils.isEmpty(className))
            return false
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val list = am.getRunningTasks(1)
        if (list != null && list.size > 0) {
            val cpn = list[0].topActivity
            if (className == cpn.className)
                return true
        }
        return false
    }

    fun isAppForeground(context: Context): Boolean {
        val activityManager = context.applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val packageName = context.applicationContext.packageName
        val appProcess = activityManager.runningAppProcesses ?: return false
        for (appProcessInfo in appProcess) {
            if (appProcessInfo.processName == packageName && appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true
            }
        }
        return false
    }

    fun isNavigationBarVisible(context: Context): Boolean {
        var isVisible = false
        val decorView = (context as Activity).window.decorView as ViewGroup
        var i = 0
        val count = decorView.childCount
        while (i < count) {
            val child = decorView.getChildAt(i)
            val id = child.id
            if (id != View.NO_ID) {
                val resourceEntryName = context
                        .getResources()
                        .getResourceEntryName(id)
                if ("navigationBarBackground" == resourceEntryName && child.visibility == View.VISIBLE) {
                    isVisible = true
                    break
                }
            }
            i++
        }
        if (isVisible) {
            val visibility = decorView.systemUiVisibility
            isVisible = visibility and View.SYSTEM_UI_FLAG_HIDE_NAVIGATION == 0
        }
        return isVisible
    }

    fun getNavigationHeight(context: Context): Int {
        val resourceId = context.resources.getIdentifier("navigation_bar_height", "dimen", "android")
        val height = context.resources.getDimensionPixelSize(resourceId)
        LogUtils.e("Navigation", "navigation height=$height")
        return height
    }

    fun getStatusHeight(context: Context): Int {
        val prefStatusBarHeight = context.getInt(PrefConstants.StatusBarHeight, -1)
        if (prefStatusBarHeight > 0) {
            return prefStatusBarHeight
        }

        var statusHeight = 0
        try {
            val c = Class.forName("com.android.internal.R\$dimen")
            val obj = c.newInstance()
            val field = c.getField("status_bar_height")
            val x = Integer.parseInt(field.get(obj).toString())
            statusHeight = context.resources.getDimensionPixelSize(x)
        } catch (e1: Exception) {
            e1.printStackTrace()
        }
        return statusHeight
    }

    fun getAppVersion(context: Context): String {
        val pm = context.packageManager

        var version = ""
        try {
            version = pm.getPackageInfo(context.packageName, PackageManager.GET_ACTIVITIES).versionName
        } catch (e: PackageManager.NameNotFoundException) {
            LogUtils.e("AppVersion", e.message!!)
        }
        return version
    }


    fun addOnKeyBoardVisibleListener(activity: Activity, onKeyBoardChangeListener: OnKeyBoardChangeListener) {
        var keyBoardHeight: Int
        val decorView = activity.window.decorView
        decorView.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            decorView.getWindowVisibleDisplayFrame(rect)

            // 可见屏幕的高度
            val displayHeight = rect.bottom - rect.top
            // 屏幕整体高度
            val height = decorView.height
            val visible = displayHeight.toDouble() / height < 0.8
            var statusBarHeight = 0
            try {
                val c = Class.forName("com.android.internal.R\$dimen")
                val obj = c.newInstance()
                val field = c.getField("status_bar_height")
                val x = Integer.parseInt(field.get(obj).toString())
                statusBarHeight = activity.applicationContext.resources.getDimensionPixelSize(x)
            } catch (e: Exception) {
                e.printStackTrace()
            }

            if (visible) {
                keyBoardHeight = height - displayHeight - statusBarHeight
                onKeyBoardChangeListener.onKeyBoardVisible(keyBoardHeight)
            } else {
                onKeyBoardChangeListener.onKeyBoardInVisible()
            }
        }

    }

    fun isNotificationEnabled(context: Context): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (context.notificationManager.importance == NotificationManager.IMPORTANCE_NONE) {
                return false
            }
        }

        val appInfo = context.applicationInfo
        val pkg = context.applicationContext.packageName
        val uid = appInfo.uid

        try {
            val appOpsClass = Class.forName(AppOpsManager::class.java.name)
            val checkOpNoThrowMethod = appOpsClass.getMethod("checkOpNoThrow", Integer.TYPE, Integer.TYPE,
                    String::class.java)
            val opPostNotificationValue = appOpsClass.getDeclaredField("OP_POST_NOTIFICATION")

            val value = opPostNotificationValue.get(Int::class.java) as Int
            return checkOpNoThrowMethod.invoke(context.appOpsManager, value, uid, pkg) as Int == AppOpsManager.MODE_ALLOWED
        } catch (e: java.lang.Exception) {
            LogUtils.e("SystemUtil", e.message!!)
        }
        return false
    }

    fun openPermissionSetting(context: Context) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri: Uri = Uri.fromParts("package", context.applicationContext.packageName, null)
        intent.data = uri
        context.startActivity(intent)
    }

    interface OnKeyBoardChangeListener {
        fun onKeyBoardVisible(keyBoardHeight: Int)

        fun onKeyBoardInVisible()
    }
}